//
//  VCSeat.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/22.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VCSeat: VCBase {
    
    private lazy var seatTicketView:SeatTicketView = {
        let ui = SeatTicketView()
        ui.frame = CGRect(x: 0, y: realHeight + MARGIN10, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - realHeight - MARGIN10)
        return ui
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_view()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        init_data()
        init_event()
    }
}

extension VCSeat {
    
    private func init_event() -> Void {
        
        seatTicketView.complete = { order,passenger in
            let vc = VCSelectSeat()
            vc.orderInfo = order
            vc.passenger = passenger
            self.pushVcHideBottomBar(title: "选择座位", vc: vc)
        }
    }
    
    private func init_data() -> Void {
        guard let userid = UserDefaults.standard.value(forKey: SP_USERID) else {
            self.show(text: "本地数据获取失败，请使用账号密码重新登录")
            return
        }
        // 拼接数据
        let request = NSMutableDictionary()
        request.setValue(userid, forKey: SP_USERID)
        request.setValue(0, forKey: SP_ORDERSTATUS)
        // 请求
        self.doPost(api: "search/order", dict: request) { (dict) in
            if self.isServerSuccess(dict: dict) != 1200 {
                self.view.addSubview(self.noDataView)
                return
            }
            // 解析数据
            let dict = dict.value(forKey: SP_BODYREQUEST) as! NSDictionary
            if dict.count == 0 {
                self.view.addSubview(self.noDataView)
                return
            }
            // 转化订单数据
            var temp = [OrderInfo]()
            if let arrs = dict.value(forKey: "orders") as? NSArray{
                for item in arrs {
                    let order = OrderInfo(dict: item as! [String : Any])
                    temp.append(order)
                }
            }
            self.seatTicketView.orderInfos = temp
            // 转化乘机人数据
            var passengers = [PassengerInfo]()
            if let arrs = dict.value(forKey: "passengers") as? NSArray{
                for item in arrs {
                    let passenger = PassengerInfo(dict: item as! [String : Any])
                    passengers.append(passenger)
                }
            }
            self.seatTicketView.passengers = passengers
        }
    }
    
    private func init_view() -> Void {
        view.addSubview(backroundWhite)
        view.addSubview(seatTicketView)
    }
}
